<script setup>
import { getSearchPostList, getSearchUserList, getSearchTopicList } from '@/axios/api/posts'
import { useInfiniteQuery } from '@tanstack/vue-query'
import { useRoute, useRouter } from 'vue-router'
import PostList from '../components/PostList.vue'
import TopicList from '../components/TopicList.vue'

import ContainerSplitOrFull from '@/components/commonUI/ContainerSplitOrFull.vue'
import LfTabs from '@/components/commonUI/LfTabs.vue'
import FansListItem from '@/views/UserHome/components/FansListItem.vue'
const route = useRoute()
const router = useRouter()
const keyword = ref(route.params.keyword)
const tabs = [
  { name: '帖子', id: 'post' },
  { name: '用户', id: 'user' },
  { name: '主题', id: 'topic' },
]
const activeIndex = ref(0)

function onTabChange(index, id, name, scrollLeft) {
  activeIndex.value = index
}

const { data, fetchNextPage, hasNextPage, isFetching, isLoading } = useInfiniteQuery({
  queryKey: ['searchPosts', keyword, activeIndex],
  queryFn: ({ pageParam = 1 }) => getSearchPostList({ keyword: keyword.value, page: pageParam}, activeIndex.value),
  getNextPageParam: (lastPage) => {
    if (lastPage.result?.total <= lastPage.result?.current_page) {
      return undefined
    }
    return lastPage.result?.current_page + 1
  },
  enabled: !!keyword,
})

// 将分页数据扁平化为一个数组
const flattenedData = computed(() => data.value?.pages.flatMap((page) => page.result.data) ?? [])

const loadMore = () => {
  if (hasNextPage.value) {
    fetchNextPage()
  }
}

const toUserHome = (data) => {
  router.push(`/user/${data.uid}`)
}

// 监听路由变化
watch(route, (newRoute) => {
  keyword.value = newRoute.params.keyword
})
</script>

<template>
  <ContainerSplitOrFull>
    <div v-infinite-scroll="loadMore" :infinite-scroll-disabled="isFetching || !hasNextPage"
      class="flex flex-col gap-3">
      <div class="main-layout">
        <div class="main-left ml-6">
          <el-card class="main-card" shadow="hover">
            <LfTabs :activeIndex="activeIndex" ref="lfTabsRef" :tabOptions="tabs" :onTopicClick="onTabChange" />
            <PostList :posts-data="flattenedData" v-if="activeIndex === 0" />
            <FansListItem v-for="item in flattenedData" :key="item.id" :item="item" v-if="activeIndex === 1"
              @click="toUserHome(item)" />
            <TopicList :posts-data="flattenedData" v-if="activeIndex === 2" />
            <div v-if="isLoading" class="p-14 text-center">加载中...</div>
            <div v-if="!isLoading && !hasNextPage" class="p-14 text-center">没有更多了</div>
          </el-card>
        </div>
      </div>

    </div>
  </ContainerSplitOrFull>
</template>
